package br.pucrio.inf.aaaong.models.domain.facade;

import java.util.ArrayList;
import java.util.List;

import br.com.caelum.vraptor.ioc.Component;
import br.pucrio.inf.aaaong.models.authentication.LoginSession;
import br.pucrio.inf.aaaong.models.database.exceptions.PostgreSQLConstraintException;
import br.pucrio.inf.aaaong.models.domain.database.DatabaseConstraint;
import br.pucrio.inf.aaaong.models.domain.database.dao.PreInscricaoDAO;
import br.pucrio.inf.aaaong.models.domain.database.dao.basic.beans.AssistenteSocialBean;
import br.pucrio.inf.aaaong.models.domain.database.dao.beans.PreInscricaoBeans;
import br.pucrio.inf.aaaong.models.domain.form.beans.PreInscricaoFormBean;
import br.pucrio.inf.aaaong.models.domain.form.converters.PreInscricaoBeansFormConverter;
import br.pucrio.inf.aaaong.models.domain.form.validation.PreInscricaoFormValidator;
import br.pucrio.inf.aaaong.models.form.errors.FormError;

@Component
public class PreInscricaoInsertFromFormFaultTolerant {
	private PreInscricaoBeansFormConverter beansBuilder;
	private PreInscricaoDAO dao;
	private PreInscricaoFormValidator validator;
	private AssistenteSocialBean assistenteSocial;
	
	public PreInscricaoInsertFromFormFaultTolerant(
			PreInscricaoBeansFormConverter beansBuilder,
			PreInscricaoDAO dao, PreInscricaoFormValidator validator,
			LoginSession login) {
		this.beansBuilder = beansBuilder;
		this.dao = dao;
		this.validator = validator;
		this.assistenteSocial = login.getAssistente();
	}

	public List<FormError> insert(PreInscricaoFormBean form) {
		List<FormError> errors = new ArrayList<FormError>();
		List<FormError> validationErrors = validator.getErrorsFrom(form);
		errors.addAll(validationErrors);
		
		PreInscricaoBeans beans = beansBuilder.from(form, this.assistenteSocial.getCpf());
		errors.addAll(beans.getErrors());
		
		if (errors.isEmpty()) {
			try {
				dao.insert(beans);
			} catch (PostgreSQLConstraintException e) {
				DatabaseConstraint constraint = DatabaseConstraint
						.getConstraint(e.getConstraintName());
				errors.add(new FormError(constraint.getMessage()));
			}
		}
		
		return errors;
	}

}
